package com.itheima.app.manager;

import cn.hutool.core.io.FileUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.VoiceMessages;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.VoiceMessagesService;
import com.itheima.vo.VoiceMessagesVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Component
public class VoiceMessagesManager {

    @Autowired
    private FastFileStorageClient client;
    @Autowired
    FdfsWebServer server;

    @DubboReference
    private VoiceMessagesService voiceMessagesService;

    @DubboReference
    private UserInfoService userInfoService;

    //保存语音
    public void saveVoice(MultipartFile soundFile) throws IOException {
        //获取当前用户id
        Long userId = UserHolder.get().getId();

        //上传语音数据获取路径
        StorePath reVoiceUrl = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), FileUtil.extName(soundFile.getOriginalFilename()), null);
        String voiceUrl = server.getWebServerUrl() + reVoiceUrl.getFullPath();
        //调用rpc
        voiceMessagesService.SaveVoice(voiceUrl,userId);
    }
    //接收语音
    public ResponseEntity receptionVoice() {
        //获取当前用户id
        Long userId = UserHolder.get().getId();

        VoiceMessages voiceMessages = voiceMessagesService.receptionVoice(userId);
        if (voiceMessages!=null) {
            //拿到语音的用户id
            Long voiceUserId = voiceMessages.getUserId();
            UserInfo userInfo = userInfoService.findByUserId(voiceUserId);
            //完善VoiceMessagesVo
            VoiceMessagesVo voiceMessagesVo = new VoiceMessagesVo();
            voiceMessagesVo.setId( new Long(voiceUserId).intValue());
            voiceMessagesVo.setAvatar(userInfo.getAvatar());
            voiceMessagesVo.setAge(userInfo.getAge());
            voiceMessagesVo.setGender(userInfo.getGender());
            voiceMessagesVo.setNickname(userInfo.getNickname());
            voiceMessagesVo.setSoundUrl(voiceMessages.getSoundUrl());
            voiceMessagesVo.setRemainingTimes(voiceMessages.getRemainingTimes());
            return ResponseEntity.ok(voiceMessagesVo);
        }else{
            return ResponseEntity.status(200).body("没有语音了");
        }

    }
}
